<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import { invoke } from '@tauri-apps/api/core';
import { 
  ElLoading, 
  ElTabs, 
  ElTabPane, 
  ElMenu, 
  ElMenuItem, 
  ElButton, 
  ElTooltip, 
  ElMessage, 
  ElScrollbar,
  ElDivider
} from 'element-plus';
import 'element-plus/dist/index.css';

// Import new improved components
import NewModelViewer from './components/NewModelViewer.vue';
import NewSearchBar from './components/NewSearchBar.vue';
import NewDetailPanel from './components/NewDetailPanel.vue';

// State management
const loading = ref(false);
const loadingInstance = ref(null);
const searchResults = ref({ meridians: [], acupoints: [] });
const selectedMeridian = ref(null);
const selectedAcupoint = ref(null);
const allMeridians = ref([]);
const meridianAcupoints = ref([]);
const showSearch = ref(false);
const activeMenuIndex = ref('1'); // Default to "经络查询"
const sidebarCollapsed = ref(false);
const showAcupointList = ref(true); // Control acupoint list visibility
const modelViewerHeight = ref(70); // Default model viewer height percentage

// Computed properties
const sidebarWidth = computed(() => {
  return sidebarCollapsed.value ? '60px' : '280px';
});

// Load all meridians when component mounts
onMounted(async () => {
  showLoading();
  try {
    allMeridians.value = await invoke('get_all_meridians');
    if (allMeridians.value.length > 0) {
      await selectMeridian(allMeridians.value[0].id);
    }
  } catch (error) {
    console.error('Failed to load meridians:', error);
    ElMessage.error('加载经络数据失败，请重试');
  } finally {
    hideLoading();
  }
});

// Helper functions for loading state
const showLoading = () => {
  loading.value = true;
  loadingInstance.value = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
};

const hideLoading = () => {
  loading.value = false;
  if (loadingInstance.value) {
    loadingInstance.value.close();
  }
};

// Handle search
const handleSearch = async (query) => {
  if (!query || query.trim() === '') {
    searchResults.value = { meridians: [], acupoints: [] };
    showSearch.value = false;
    return;
  }
  
  showLoading();
  try {
    const results = await invoke('search', { query });
    searchResults.value = results;
    showSearch.value = true;
  } catch (error) {
    console.error('Search failed:', error);
    ElMessage.error('搜索失败，请重试');
  } finally {
    hideLoading();
  }
};

// Clear search
const clearSearch = () => {
  searchResults.value = { meridians: [], acupoints: [] };
  showSearch.value = false;
};

// Select a meridian
const selectMeridian = async (meridianId) => {
  showLoading();
  try {
    // Get meridian details
    selectedMeridian.value = await invoke('get_meridian_detail', { meridianId });
    
    // Get acupoints for this meridian
    meridianAcupoints.value = await invoke('get_meridian_acupoints', { meridianId });
    
    // Clear selected acupoint
    selectedAcupoint.value = null;
    
    // Hide search results
    showSearch.value = false;
    
    // Show acupoint list when a meridian is selected
    showAcupointList.value = true;
  } catch (error) {
    console.error('Failed to select meridian:', error);
    ElMessage.error('选择经络失败，请重试');
  } finally {
    hideLoading();
  }
};

// Select an acupoint
const selectAcupoint = async (acupointId) => {
  showLoading();
  try {
    selectedAcupoint.value = await invoke('get_acupoint_detail', { acupointId });
    
    // Hide search results
    showSearch.value = false;
  } catch (error) {
    console.error('Failed to select acupoint:', error);
    ElMessage.error('选择穴位失败，请重试');
  } finally {
    hideLoading();
  }
};

// Handle item selection from search results
const handleSelectSearchItem = (item) => {
  if (item.type === 'meridian') {
    selectMeridian(item.id);
  } else if (item.type === 'acupoint') {
    selectAcupoint(item.id);
  }
};

// Toggle sidebar collapse state
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value;
};

// Toggle acupoint list visibility
const toggleAcupointList = () => {
  showAcupointList.value = !showAcupointList.value;
};

// Handle menu selection
const handleMenuSelect = (index) => {
  activeMenuIndex.value = index;
};

// Adjust viewer heights - allows user to change the proportion of model to detail panel
const adjustViewerHeight = (delta) => {
  const newHeight = modelViewerHeight.value + delta;
  if (newHeight >= 50 && newHeight <= 85) {
    modelViewerHeight.value = newHeight;
  }
};

// Watch for changes in selectedAcupoint
watch(() => selectedAcupoint.value, (newValue) => {
  if (newValue) {
    // When an acupoint is selected, increase the model viewer height for better visibility
    modelViewerHeight.value = 70; // Default balance
  }
});
</script>

<template>
  <div class="app-container">
    <!-- Left sidebar with menu -->
    <aside class="app-sidebar" :style="{ width: sidebarWidth }">
      <div class="app-logo">
        <img src="/tauri.svg" alt="Logo" class="logo-image" />
        <span v-if="!sidebarCollapsed" class="logo-text">经络穴位</span>
      </div>
      
      <ElMenu
        class="app-menu"
        :default-active="activeMenuIndex"
        :collapse="sidebarCollapsed"
        background-color="#001529"
        text-color="#fff"
        active-text-color="#409EFF"
        @select="handleMenuSelect"
      >
        <ElMenuItem index="1">
          <el-icon><i class="el-icon-meridian"></i></el-icon>
          <template #title>经络查询</template>
        </ElMenuItem>
        <ElMenuItem index="2" disabled>
          <el-icon><i class="el-icon-health"></i></el-icon>
          <template #title>养生知识</template>
        </ElMenuItem>
        <ElMenuItem index="3" disabled>
          <el-icon><i class="el-icon-consultation"></i></el-icon>
          <template #title>中医问诊</template>
        </ElMenuItem>
      </ElMenu>
      
      <div class="sidebar-toggle" @click="toggleSidebar">
        <el-icon>
          <i :class="sidebarCollapsed ? 'el-icon-right' : 'el-icon-left'"></i>
        </el-icon>
      </div>
    </aside>
    
    <!-- Main content area -->
    <div class="main-area">
      <!-- Header with search bar -->
      <header class="app-header">
        <div class="header-title-section">
          <h1 class="app-title">经络穴位3D查询系统</h1>
        </div>
        <NewSearchBar
          @search="handleSearch"
          @clear="clearSearch"
          :search-results="searchResults"
          :show-results="showSearch"
          @select="handleSelectSearchItem"
        />
        <div class="header-actions">
          <ElTooltip content="全屏" placement="bottom">
            <ElButton circle icon="FullScreen" />
          </ElTooltip>
          <ElTooltip content="设置" placement="bottom">
            <ElButton circle icon="Setting" />
          </ElTooltip>
        </div>
      </header>
      
      <!-- Main content with meridian list and 3D viewer -->
      <div class="main-content">
        <!-- Left panel - Meridian list when in meridian query mode -->
        <aside v-if="activeMenuIndex === '1'" class="content-sidebar">
          <!-- Top section with meridian list (always visible) -->
          <div class="meridian-section">
            <h2 class="sidebar-title">经络列表</h2>
            <ElScrollbar height="calc(100% - 40px)">
              <ul class="meridian-list">
                <li
                  v-for="meridian in allMeridians"
                  :key="meridian.id"
                  :class="{ active: selectedMeridian && meridian.id === selectedMeridian.id }"
                  @click="selectMeridian(meridian.id)"
                >
                  <span class="meridian-no">{{ meridian.no }}</span>
                  <span class="meridian-name">{{ meridian.name }}</span>
                </li>
              </ul>
            </ElScrollbar>
          </div>
          
          <!-- Toggle button for acupoint list -->
          <div class="acupoint-list-toggle" v-if="selectedMeridian">
            <ElButton 
              type="primary" 
              size="small" 
              @click="toggleAcupointList"
              :icon="showAcupointList ? 'ArrowUp' : 'ArrowDown'"
            >
              {{ showAcupointList ? '收起穴位' : '显示穴位' }}
            </ElButton>
          </div>
          
          <!-- Bottom section with acupoint list (can be toggled) -->
          <div v-if="selectedMeridian && showAcupointList" class="acupoint-list-container">
            <h3 class="acupoint-list-title">{{ selectedMeridian.name }}穴位</h3>
            <ElScrollbar height="calc(100% - 40px)">
              <div class="acupoint-list">
                <div
                  v-for="acupoint in meridianAcupoints"
                  :key="acupoint.id"
                  :class="{ active: selectedAcupoint && acupoint.id === selectedAcupoint.id }"
                  class="acupoint-item"
                  @click="selectAcupoint(acupoint.id)"
                >
                  <span class="acupoint-no">{{ acupoint.no }}</span>
                  <span class="acupoint-name">{{ acupoint.name }}</span>
                </div>
              </div>
            </ElScrollbar>
          </div>
        </aside>
        
        <!-- Main area - 3D Model + Detail Panel -->
        <div class="view-area">
          <!-- Resizable panels -->
          <div class="model-view-container" :style="{ height: `${modelViewerHeight}%` }">
            <NewModelViewer
              :selected-meridian="selectedMeridian"
              :selected-acupoint="selectedAcupoint"
            />
            
            <!-- Resize handle -->
            <div class="resize-handle">
              <div class="resize-controls">
                <ElButton 
                  size="small" 
                  circle 
                  icon="ArrowUp" 
                  @click="adjustViewerHeight(5)"
                  title="增加模型区域"
                ></ElButton>
                <ElDivider direction="vertical" />
                <ElButton 
                  size="small" 
                  circle 
                  icon="ArrowDown" 
                  @click="adjustViewerHeight(-5)"
                  title="减少模型区域"
                ></ElButton>
              </div>
            </div>
          </div>
          
          <div class="detail-container" :style="{ height: `${100 - modelViewerHeight}%` }">
            <NewDetailPanel
              :selected-meridian="selectedMeridian"
              :selected-acupoint="selectedAcupoint"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style>
:root {
  --primary-color: #1890ff;
  --dark-primary: #001529;
  --secondary-color: #2c3e50;
  --accent-color: #52c41a;
  --text-color: #333;
  --light-text: #f5f5f5;
  --bg-color: #f0f2f5;
  --sidebar-width: 280px;
  --sidebar-collapsed-width: 60px;
  --header-height: 64px;
  --border-radius: 4px;
  --box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  --transition-duration: 0.3s;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB',
    'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
  color: var(--text-color);
  background-color: var(--bg-color);
  overflow: hidden;
}

.app-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
  position: relative;
}

/* App Sidebar */
.app-sidebar {
  height: 100vh;
  background-color: var(--dark-primary);
  transition: width var(--transition-duration);
  display: flex;
  flex-direction: column;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

.app-logo {
  height: var(--header-height);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 16px;
  color: white;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  overflow: hidden;
}

.logo-image {
  width: 32px;
  height: 32px;
  margin-right: 10px;
}

.logo-text {
  font-size: 18px;
  font-weight: bold;
  white-space: nowrap;
}

.app-menu {
  flex: 1;
  border-right: none !important;
}

.sidebar-toggle {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  cursor: pointer;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.sidebar-toggle:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

/* Create custom Element Plus icons */
.el-icon-meridian:before {
  content: "🧠";
}

.el-icon-health:before {
  content: "💪";
}

.el-icon-consultation:before {
  content: "👨‍⚕️";
}

.el-icon-left:before {
  content: "◀";
}

.el-icon-right:before {
  content: "▶";
}

/* Main Area */
.main-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.app-header {
  height: var(--header-height);
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  padding: 0 20px;
  z-index: 100;
}

.header-title-section {
  min-width: 200px;
}

.app-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--text-color);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
  margin-left: 16px;
}

/* Main Content Area */
.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content-sidebar {
  width: 300px;
  background-color: white;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.meridian-section {
  display: flex;
  flex-direction: column;
  height: 60%;
  overflow: hidden;
}

.sidebar-title {
  padding: 16px;
  font-size: 1rem;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.meridian-list {
  list-style: none;
  height: calc(100% - 58px);
}

.meridian-list li {
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f2f6fc;
  display: flex;
  align-items: center;
  transition: all 0.2s;
}

.meridian-list li:hover {
  background-color: #f5f7fa;
}

.meridian-list li.active {
  background-color: #e6f7ff;
  color: var(--primary-color);
  border-right: 3px solid var(--primary-color);
}

.meridian-no {
  font-weight: bold;
  margin-right: 10px;
  color: var(--primary-color);
}

.acupoint-list-toggle {
  display: flex;
  justify-content: center;
  padding: 8px 0;
  background-color: #f5f7fa;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

.acupoint-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.acupoint-list-title {
  padding: 12px 16px;
  font-size: 1rem;
  font-weight: bold;
  background-color: #f5f7fa;
}

.acupoint-list {
  display: flex;
  flex-wrap: wrap;
  padding: 12px;
  gap: 12px;
}

.acupoint-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: var(--border-radius);
  cursor: pointer;
  transition: all 0.2s;
  flex: 0 0 calc(50% - 12px);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid #ebeef5;
}

.acupoint-item:hover {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  transform: translateY(-2px);
}

.acupoint-item.active {
  background-color: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.acupoint-item.active .acupoint-no {
  color: white;
}

.acupoint-no {
  font-weight: bold;
  margin-right: 8px;
  color: var(--primary-color);
}

.view-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: var(--bg-color);
}

.model-view-container {
  position: relative;
  width: 100%;
  transition: height 0.3s ease;
}

.detail-container {
  width: 100%;
  overflow: hidden;
  transition: height 0.3s ease;
}

.resize-handle {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.resize-controls {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 20px;
  padding: 2px 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
}

/* Responsive design */
@media (max-width: 992px) {
  .content-sidebar {
    width: 250px;
  }
}

@media (max-width: 768px) {
  .app-container {
    flex-direction: column;
  }
  
  .app-sidebar {
    width: 100% !important;
    height: auto;
    flex-direction: row;
  }
  
  .app-logo {
    width: 60px;
    height: 60px;
  }
  
  .app-menu {
    flex-direction: row;
  }
  
  .sidebar-toggle {
    width: 60px;
    height: 60px;
  }
  
  .main-content {
    flex-direction: column;
  }
  
  .content-sidebar {
    width: 100%;
    height: 40%;
  }
  
  .meridian-section,
  .acupoint-list-container {
    height: auto;
    flex: 1;
  }
  
  .meridian-list,
  .acupoint-list {
    height: auto;
    max-height: 200px;
  }
  
  .view-area {
    height: 60%;
  }
  
  .model-view-container {
    height: 60% !important;
  }
  
  .detail-container {
    height: 40% !important;
  }
}
</style>